<script setup lang="ts">
import {
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NForm,
  NFormItem,
  NModal,
  useMessage
} from 'naive-ui'
import { h, onMounted, reactive, ref } from 'vue'
import TableView from '@/components/TableView.vue'
import useFlush from '@/hooks/useFlush'
import { sendRequest } from '@/utils/api'
import type { HttpResponsePagination } from '@/utils/http'
import type { InterpreterModel } from '@/api/interpreter'
import { useRouter } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'

const message = useMessage()
const router = useRouter()
useFlush('flushInterpreterTable', () => queryTableData())

const formData = reactive<{ interpreterName: string | null }>({
  interpreterName: null
})

const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})

const tableData = ref<InterpreterModel[]>([])
const tableLoading = ref(false)
const queryTableData = async (flush = false) => {
  if (flush) paginationReactive.page = 1
  try {
    tableLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<InterpreterModel>>({
      module: 'interpreter',
      api: 'list',
      override: {
        params: {
          limit: paginationReactive.pageSize,
          page: paginationReactive.page,
          ...formData
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)

    tableData.value = res.data.list
    paginationReactive.itemCount = res.data.totalCount
  } catch (error) {
    console.log(error)
  } finally {
    tableLoading.value = false
  }
}
const columns: DataTableColumns<InterpreterModel> = [
  {
    title: '姓名',
    key: 'interpreterName'
  },
  {
    title: '手机号',
    key: 'phoneNumber'
  },
  {
    title: '性别',
    key: 'sexValue'
  },
  {
    title: '身份证',
    key: 'idNumber'
  },
  {
    title: '级别',
    key: 'levelValue'
  },
  {
    title: '讲解次数',
    key: 'explanationsNumber'
  },
  // {
  //   title: '今日状态',
  //   key: 'todayStatus'
  // },
  {
    title: '操作',
    key: 'action',
    align: 'center',
    width: 150,
    render: (e) => {
      return h(
        NSpace,
        {
          justify: 'center',
          wrap: false
        },
        {
          default: () => [
            h(
              NButton,
              {
                quaternary: true,
                type: 'primary',
                onClick: () => handleCollectionAction('u', e.id)
              },
              {
                default: () => '编辑'
              }
            ),
            h(
              NButton,
              {
                quaternary: true,
                type: 'error',
                onClick: () => handleCollectionAction('d', e.id)
              },
              {
                default: () => '删除'
              }
            )
          ]
        }
      )
    }
  }
]

const deleteModalVisible = ref(false)
const deleteId = ref<number | null>(null)
const handleCollectionDelete = (id: number) => {
  deleteId.value = id
  deleteModalVisible.value = true
}
const confirmDelete = async () => {
  if (!deleteId.value) return
  console.log('confirm delete')
  try {
    const [error, res] = await sendRequest({
      module: 'interpreter',
      api: 'delete',
      override: {
        data: [deleteId.value]
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    queryTableData()
  } catch (error) {
    if (error instanceof Error) message.error(error.message)
  } finally {
    deleteModalVisible.value = false
  }
}
function handleCollectionAction(type: 'c' | 'u' | 'd', id?: number) {
  if (type === 'd') return handleCollectionDelete(id!)
  router.push({
    name: type === 'c' ? 'InterpreterAdd' : 'InterpreterEdit',
    params: {
      id
    },
    query: {
      type,
      redirect: router.currentRoute.value.fullPath
    }
  })
}

onMounted(() => queryTableData())
</script>

<template>
  <TableView class="interpreter">
    <template #form>
      <NForm label-placement="left" :show-feedback="false" class="interpreter-form"
        @keydown.enter="queryTableData(true)">
        <NFormItem label="名称：">
          <NInput v-model:value="formData.interpreterName" placeholder="名称" clearable />
        </NFormItem>

        <NButton :disabled="tableLoading" :loading="tableLoading" color="#6CB187" ghost style="min-width: 78rem"
          @click="queryTableData(true)">
          查询
        </NButton>

        <NButton color="#6CB187" class="interpreter-add-button" @click="handleCollectionAction('c')">
          新增讲解员
        </NButton>
      </NForm>
    </template>
    <template #table="props">
      <NDataTable v-bind="props" :data="tableData" :columns="columns" :loading="tableLoading" bordered />
    </template>
    <template #pagination>
      <NPagination show-size-picker show-quick-jumper :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount" :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize" @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize">
        <template #suffix>页</template>
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="deleteModalVisible">
    <VDialogContent @close="deleteModalVisible = false" @submit="confirmDelete" title="删除提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
.interpreter {
  padding: 29rem 30rem;
  gap: 25rem 0;
}

.interpreter-form {
  display: flex;
  gap: 10rem;

  .n-form-item {
    flex: 0 0 260rem;
  }

  .n-form-item:nth-child(n + 2) {
    flex: 1;
  }

  .interpreter-add-button {
    margin-left: auto;
  }
}

@media screen and (max-width: 1919px) {
  .interpreter-form {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 15rem 20rem;
  }

  .interpreter-add-button {
    grid-column: 5 / -1;
  }
}
</style>
